<template>
  <!-- <div height="20px"></div> -->
  <div>
    <el-container>
      <el-header>
        <h1>上传密文文件</h1>
      </el-header>
      <el-main>
        <el-row></el-row>
        <el-row></el-row>
        <el-row :gutter="10">
          <!-- <el-col :span="50" :offset="4"> -->
          <el-col :span="10" :offset="7">
            <el-input placeholder="请输入待上传文档的标题" v-model="file_title"></el-input>
          </el-col>
        </el-row>

        <div class="center-component">
          <el-upload class="upload-demo" drag action='#' :before-upload="beforeFileUpload"
            :http-request="customHttpRequest" :file-list="fileList" multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传txt/pdf文件</div>
          </el-upload>
        </div>
        <br />
        <div class="center-component">
          <el-button type="primary" @click="preview_file" icon="el-icon-document">查看文本</el-button>
          <el-button type="primary" @click="extract_keywords" icon="el-icon-collection-tag">提取关键词</el-button>
          <el-button type="primary" @click="upload_encrypt_file" icon="el-icon-upload2">上传密文文件</el-button>
        </div>
      </el-main>
    </el-container>

    <el-dialog title="查看文本" :visible.sync="preview_file_dialog_visible">
      <h1>
        <pre>{{ file_title }}</pre>
      </h1>
      <el-input type="textarea" :rows="23" readonly v-model="file_content">
      </el-input>

    </el-dialog>

    <el-dialog title="提取关键字" :visible.sync="extract_keywords_dialog_visible">
      <el-tag v-for="term_item in terms" :key="term_item.term" closable @close="handleClose(term_item)"
        :type="term_item.type">
        {{ term_item.term }}
      </el-tag>
      <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
        @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="extract_keywords_dialog_visible = false">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import fs from 'fs'
import { ipcRenderer } from "electron";
import axios from 'axios';

export default {
  data() {
    return {
      preview_file_dialog_visible: false,
      extract_keywords_dialog_visible: false,
      fileList: [], // 存储上传的文件列表  
      file_title: "",
      file_content: "",
      file_content_base64: "",
      file_type: "",
      terms: [],
      inputVisible: false,
      inputValue: ''
    };
  },
  methods: {
    handleClose(term) {
      this.terms.splice(this.terms.indexOf(term), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.terms.push(
          {
            term: inputValue,
            freq: 1
          }
        );
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

    beforeFileUpload(file) {
      fs.readFile(file.path, async (err, data) => {
        if (err) {
          console.error('Error reading the file:', err);
          return false;
        }
        this.$message({
          message: '正在读取文件，请稍后...',
        });
        this.file_title = file.name.split('.')[0];
        this.file_type = file.name.split('.')[1];
        // file_type 转小写
        this.file_type = this.file_type.toLowerCase();
        this.file_content_base64 = data.toString('base64');
        if (this.file_type == "txt") {
          this.file_content = data.toString();
        } else if (this.file_type == "pdf") {
          const resp = await axios.post('http://127.0.0.1:5000/GetTextFromPdf', {
            pdf_base64: this.file_content_base64
          })
          this.file_content = resp.data.text;
        }
        this.$message({
          message: '读取文件成功！',
          type: 'success'
        });
      });
      this.fileList.push(file);
      return true;
    },

    preview_file() {
      if (this.file_content_base64 == "") {
        this.$message({
          message: '请先上传文件！',
          type: 'warning'
        });
        return;
      }
      if (this.file_content == "") {
        this.$message({
          message: '请等待文件读取完成！',
          type: 'warning'
        });
        return;
      }
      this.preview_file_dialog_visible = true;
    },

    extract_keywords() {
      if (this.file_content_base64 == "") {
        this.$message({
          message: '请先上传文件！',
          type: 'warning'
        });
        return;
      }
      if (this.file_content == "") {
        this.$message({
          message: '请等待文件读取完成！',
          type: 'warning'
        });
        return;
      }
      ipcRenderer.invoke("ExtractKeywords", { content: this.file_content }).then((res) => {
        this.terms = res;
        this.extract_keywords_dialog_visible = true;
      });
    },

    customHttpRequest(file) {
      // 使用你喜欢的 HTTP 库（比如 Axios）来发起文件上传请求
      // 这里仅为演示，实际情况中需要根据你的后端 API 进行调整
      return true;
    },

    upload_encrypt_file() {
      if (this.file_content_base64 == "") {
        this.$message({
          message: '请先上传文件！',
          type: 'warning'
        });
        return;
      }
      if (this.file_content == "") {
        this.$message({
          message: '请等待文件读取完成！',
          type: 'warning'
        });
        return;
      }
      if (this.terms.length == 0) {
        this.$message({
          message: '请先提取关键词！',
          type: 'warning'
        });
        return;
      }
      if (this.file_title == "") {
        this.$message({
          message: '请输入文件标题！',
          type: 'warning'
        });
        return;
      }
      this.$message({
        message: '正在上传，请稍后...',
      });
      ipcRenderer.invoke("UploadEncFile", {
        title: this.file_title,
        content_base64: this.file_content_base64,
        file_type: this.file_type,
        terms: this.terms
      }).then((res) => {
        console.log(res);
        if (res) {
          this.$message({
            message: '上传密文文件成功！',
            type: 'success'
          });
        } else {
          this.$message({
            message: '上传密文文件失败！',
            type: 'error'
          });
        }
      });
    },
  }
}
</script>



<style>
.el-header {
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-tag+.el-tag {
  margin-left: 10px;
  margin-top: 8px;
}

.button-new-tag {
  margin-left: 10px;
}

.input-new-tag {
  margin-left: 10px;
  width: 90px;
}

.center-component {
  /* width: 500px; */
  margin-top: 20px;
  display: flex;
  justify-content: center;
  /* 水平居中 */
}
</style>